package io.hellsinger.vortex.ui.screen.storage.list

import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout.LayoutParams.WRAP_CONTENT
import androidx.recyclerview.widget.RecyclerView
import io.hellsinger.navigation.screen.ListScreenController
import io.hellsinger.theme.vortex.VortexSettings
import io.hellsinger.viewmodel.BitViewModel
import io.hellsinger.vortex.data.model.PENDING_TRANSITION
import io.hellsinger.vortex.data.model.PathItem
import io.hellsinger.vortex.data.model.PendingTransition
import io.hellsinger.vortex.data.model.PendingTransition.Companion.TYPE_COPY
import io.hellsinger.vortex.data.model.PendingTransition.Companion.TYPE_MOVE
import io.hellsinger.vortex.data.model.toTwoLine
import io.hellsinger.vortex.di.createListMenuTaskViewModel
import io.hellsinger.vortex.ui.component.adapter.ItemAdapter
import io.hellsinger.vortex.ui.component.adapter.Items
import io.hellsinger.vortex.ui.component.adapter.UnsupportedViewTypeException
import io.hellsinger.vortex.ui.component.adapter.listener.ItemListener
import io.hellsinger.vortex.ui.component.dp
import io.hellsinger.vortex.ui.component.drawable.RoundedCornerDrawable
import io.hellsinger.vortex.ui.component.item.title.TitleItemView
import io.hellsinger.vortex.ui.component.item.twoline.TwoLineItemView
import io.hellsinger.vortex.ui.dsl.frameParams
import io.hellsinger.vortex.ui.screen.storage.list.StorageListMenuTaskViewModel.UiState
import io.hellsinger.vortex.ui.screen.storage.transaction.StorageTransactionScreenController
import io.hellsinger.vortex.ui.screen.storage.transaction.StorageTransactionScreenController.Args.Companion.LOAD_TYPE_COPY
import io.hellsinger.vortex.ui.screen.storage.transaction.StorageTransactionScreenController.Args.Companion.LOAD_TYPE_MOVE

class StorageListMenuTaskScreenController(
    private val context: Context,
) : ListScreenController<PathItem>(),
    ItemListener,
    BitViewModel.UiStateUpdateCollector<UiState> {
    private var viewModel: StorageListMenuTaskViewModel? = null

    override val adapter =
        ItemAdapter(
            listener = this,
            viewProvider = { parent, viewType ->
                when (viewType) {
                    Items.PENDING_TRANSITION ->
                        TwoLineItemView(parent.context).apply {
                            setTitleColor(VortexSettings.colors { key_storage_list_menu_task_item_title_color })
                            setDescriptionColor(VortexSettings.colors { key_storage_list_menu_task_item_description_color })
                            setRippleColor(VortexSettings.colors { key_storage_list_menu_task_item_ripple_color })
                            setBackgroundColor(VortexSettings.colors { key_storage_list_menu_task_item_surface_color })
                        }

                    Items.TITLE ->
                        TitleItemView(context).apply {
                            setTitleColor(VortexSettings.colors { key_storage_list_menu_task_title_color })
                        }

                    else -> throw UnsupportedViewTypeException(viewType)
                }
            },
            viewBinder = { holder, item ->
                when (holder.itemViewType) {
                    Items.PENDING_TRANSITION -> {
                        item as PendingTransition
                        holder.view.tag = holder.bindingAdapterPosition
                        (holder.view as TwoLineItemView).onBind(item.toTwoLine(args))
                    }
                }
            },
        )

    override val usePopupMode: Boolean
        get() = true

    override fun onBackActivatedImpl(): Boolean = false

    override fun onApplyRecyclerView(recycler: RecyclerView) {
        super.onApplyRecyclerView(recycler)
        recycler.frameParams(MATCH_PARENT, WRAP_CONTENT) {
            gravity = Gravity.BOTTOM
        }
        recycler.background =
            RoundedCornerDrawable(
                color = VortexSettings.colors { key_storage_list_menu_task_background_color },
                topLeft = context.dp(16F),
                topRight = context.dp(16F),
            )
    }

    override fun onPrepareImpl() {
        if (viewModel == null) {
            viewModel = context.createListMenuTaskViewModel()
        }
        viewModel?.collectUiState(this)
        viewModel?.collectSharedState()
    }

    override fun onFocusImpl() {
    }

    override fun onHideImpl() {
    }

    override fun onDestroyImpl() {
    }

    override fun onSaveImpl(
        buffer: Bundle,
        prefix: String,
    ): Boolean = false

    override fun onRestoreImpl(
        buffer: Bundle,
        prefix: String,
    ): Boolean = false

    override fun onItemClick(
        view: View,
        position: Int,
    ) {
        when (val item = viewModel?.getUiState()?.items?.get(position)) {
            is PendingTransition -> {
                val dest = args ?: return
                router?.navigate(
                    screen = StorageTransactionScreenController(context),
                    args =
                        StorageTransactionScreenController.Args.Transition(
                            items = item.value,
                            dest = dest,
                            type =
                                when (item.type) {
                                    TYPE_COPY -> LOAD_TYPE_COPY
                                    TYPE_MOVE -> LOAD_TYPE_MOVE
                                    else -> throw Throwable("Unsupported pending type ${item.type}")
                                },
                        ),
                )
            }
        }
    }

    override fun onLongItemClick(
        view: View,
        position: Int,
    ): Boolean = false

    override suspend fun emit(
        event: Int,
        state: UiState,
    ) {
        adapter.replace(state.items)
    }
}
